﻿using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model;
using LdtJudge.DataEngine.Model.DataModel;
using LdtJudge.DataEngine.Model.DataModel.ElementNode;
using LdtJudge.DataEngine.Model.OptimizationModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;

namespace LdtJudge.DataEngine.Common
{
    /// <summary>
    /// XML文件帮助类
    /// </summary>
    public class XmlUtilCommon
    {
        #region 基础信息
        public DataContext dataContext;
        #endregion

        #region 优选配置解析公共方法
        /// <summary>
        /// 获取配置类集合
        /// </summary>
        /// <param name="xmlDocument">XML对象</param>
        /// <returns></returns>
        public List<ConfigNodeModel> ReadConfigNodeList(XmlNodeList xmlNodeList, ConfigNodeModel configNodeModel, List<ConfigNodeModel> configNodeModelList)
        {
            if (configNodeModelList == null)
            {
                configNodeModelList = new List<ConfigNodeModel>();
            }
            foreach (XmlNode xmlnode in xmlNodeList)
            {
                ConfigNodeModel configNode = new ConfigNodeModel();
                configNode.Uid = Snowflake.Instance().GetId().ToString();
                if (configNodeModel.XmlPath == "")
                {
                    configNode.XmlPath = xmlnode.Name;
                }
                else
                {
                    configNode.XmlPath = configNodeModel.XmlPath + @"\" + xmlnode.Name;
                }
                configNode.xmlNode = xmlnode;
                configNode.Name = xmlnode.Name;
                configNode.ParentID = configNodeModel.Uid;
                Dictionary<string, string> dicAttribute = new Dictionary<string, string>();
                if (xmlnode.Attributes != null)
                {


                    foreach (XmlAttribute attribute in xmlnode.Attributes)
                    {
                        dicAttribute.Add(attribute.Name, attribute.Value);
                    }
                }
                configNode.DicAttribute = dicAttribute;
                configNodeModelList.Add(configNode);
                ReadConfigNodeList(xmlnode.ChildNodes, configNode, configNodeModelList);
            }

            return configNodeModelList;
        }

        /// <summary>
        /// 将XML转换为配置文件类ConfigNodeModel
        /// </summary>
        /// <param name="xmlDocument">配置文件</param>
        /// <returns></returns>
        public List<ConfigNodeModel> ReadConfigNode(XmlDocument xmlDocument)
        {
            List<ConfigNodeModel> configNodeModelList = new List<ConfigNodeModel>();
            XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/*");
            ConfigNodeModel configNodeModel = new ConfigNodeModel();
            configNodeModel.Uid = "0";
            configNodeModel.XmlPath = "";
            configNodeModelList.AddRange(ReadConfigNodeList(xmlNodeList, configNodeModel, null));

            return configNodeModelList;
        }
        #endregion

        #region XML文件与模型转换公用方法

        /// <summary>
        /// 解析完成XML格式并输出
        /// </summary>
        /// <param name="elementNodes">将要素内容转换为XML</param>
        /// <returns></returns>
        public XmlDocument AnalyticalXmlDocument(List<ElementNodeModel> elementNodes)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement rootElement = xmlDocument.CreateElement("temap");
            AnlyticalXmlNodel(elementNodes, rootElement, "0", xmlDocument);
            xmlDocument.AppendChild(rootElement);
            XmlDocument xmlDocumentreust = new XmlDocument();
            foreach (XmlNode node in xmlDocument.SelectNodes("temap/*"))
            {
                xmlDocumentreust.LoadXml(node.OuterXml);
            };
            return xmlDocumentreust;
        }

        /// <summary>
        /// 转换XML
        /// </summary>
        /// <param name="elementNodesList">要素集合</param>
        /// <param name="xmlElementPranet">节点信息</param>
        /// <param name="pid">父节点信息</param>
        /// <param name="xmlDocument">返回XML内容</param>
        public void AnlyticalXmlNodel(List<ElementNodeModel> elementNodesList, XmlElement xmlElementPranet, string pid, XmlDocument xmlDocument)
        {
            List<ElementNodeModel> elementNodeList = elementNodesList.Where(a => a.ParentId == pid).ToList();
            List<ElementNodeModel> elementNode = elementNodeList.Where(a => a.IsNode == "1").ToList();
            //节点解析
            foreach (ElementNodeModel nodemodel in elementNode)
            {
                ///创建节点
                XmlElement xmlElementNodel = xmlDocument.CreateElement(nodemodel.Name);
                List<ElementNodeModel> elementAttice = elementNodesList.Where(a => a.IsNode == "0" && a.ParentId == nodemodel.Id).ToList();
                foreach (ElementNodeModel nodemodelat in elementAttice)
                {
                    ///创建节点
                    xmlElementNodel.SetAttribute(nodemodelat.Name, nodemodelat.OriginalTextList[0]);

                }
                AnlyticalXmlNodel(elementNodesList, xmlElementNodel, nodemodel.Id, xmlDocument);

                xmlElementPranet.AppendChild(xmlElementNodel);
            }
            //属性添加

        }

        /// <summary>
        /// 生成案件数据来源
        /// </summary>
        /// <returns></returns>
        public List<DataModel> GenerateDataSources()
        {
            List<DataModel> dataModelList = new List<DataModel>();
            if (dataModelList.Count == 0)
            {
                foreach (XmlNode xmlNode in dataContext.DataLayerAns.AnalysisResultsXml.ChildNodes)
                {
                    NodeChangeModel(xmlNode, dataModelList, xmlNode.Name, "", xmlNode.Name);
                }
            }
            return dataModelList;
        }

        /// <summary>
        /// 根据分析结果转换
        /// </summary>
        /// <returns></returns>
        public List<DataModel> AnalysisConvertDataModel()
        {
            List<DataModel> resultModelList = new List<DataModel>();
            if (dataContext.DataLayerAns.ElementNodeModelsList != null && dataContext.DataLayerAns.ElementNodeModelsList.Any())
            {
                AddEelmentNodeSources(dataContext.DataLayerAns.ElementNodeModelsList, resultModelList);
            }
            else
            {
                //获取
                foreach (XmlNode xmlNode in dataContext.DataLayerAns.AnalysisResultsXml.ChildNodes)
                {
                    NodeChangeModel(xmlNode, resultModelList, xmlNode.Name, "", xmlNode.Name);
                }
                DataSoursModel dataSoursModel = new DataSoursModel();
                dataSoursModel.dataModelList = new List<DataModel>();
                dataSoursModel.dataModelList = resultModelList;
            }

            return resultModelList;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="elementDataList"></param>
        /// <param name="datalList"></param>
        public void AddEelmentNodeSources(List<ElementNodeModel> elementDataList, List<DataModel> datalList)
        {
            foreach (ElementNodeModel elementData in elementDataList.Where(a => a.Path.IndexOf("@") < 0 && a.IsNode == "1"))
            {
                DataModel dataModel = new DataModel();
                dataModel.ID = elementData.Id;
                if (elementData.ParentId == "0")
                {
                    dataModel.ParentId = "";

                }
                else
                {
                    dataModel.ParentId = elementData.ParentId;

                }
                dataModel.State = "1";
                dataModel.XmlPath = elementData.Path.Replace("\\", "/");
                dataModel.AttributesList = new List<AttributeInfo>();

                foreach (ElementNodeModel elementAttribut in elementDataList.Where(a => a.IsNode == "0" && a.ParentId == elementData.Id))
                {
                    AttributeInfo attribute = new AttributeInfo();
                    List<string> strList = elementAttribut.Path.Split('\\').ToList();
                    string attrName = strList[strList.Count - 1];
                    string xmlpath = "";
                    strList.Remove(attrName);
                    foreach (string path in strList)
                    {
                        if (xmlpath == "")
                        {
                            xmlpath = path;
                        }
                        else
                        {
                            xmlpath = xmlpath + "/" + path;
                        }
                    }
                    attribute.Name = attrName;
                    attribute.DictionariesCode = elementAttribut.DictionariesCode;
                    attribute.sourceList = new List<Source>();
                    Source source = new Source();
                    source.IsCheck = "1";
                    if(!string.IsNullOrWhiteSpace(elementAttribut.OrigianlTextStr))
                        source.OriginalText = HttpHelp.EnDataBase64(elementAttribut.OrigianlTextStr);
                    source.ParagraphCode = elementAttribut.ParagraphName;
                    source.AnalysisStatus = "1";
                    if (elementAttribut.OriginalTextList[0] == "原代")
                    {
                        string ff = "";
                    }
                    source.SaveValue = elementAttribut.OriginalTextList[0];
                    source.ExtValue = elementAttribut.ExtOriginalText;
                    if (string.IsNullOrEmpty(source.ExtValue))
                    {
                        source.ExtValue = elementAttribut.OriginalTextList[0];
                    }
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.SourceID = dataContext.DataLayerAns.SF_ID;
                    source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                    if (!string.IsNullOrEmpty(source.ExtValue) && (!dataContext.DataLayerAns.IsParagraphAnalysis.HasValue || dataContext.DataLayerAns.IsParagraphAnalysis==false))
                    {
                        source.OriginalLocation = elementAttribut.OrigianlTextStr.IndexOf(source.ExtValue).ToString();
                        if (!string.IsNullOrEmpty(source.OriginalLocation) && source.OriginalLocation!="-1")
                        {
                            source.Location = dataContext.DataLayerAns.FengXiCanShu.Juanzongneirong?.IndexOf(elementAttribut.OrigianlTextStr).ToString();
                            if (source.Location!="-1")
                            {
                                source.Location = (int.Parse(source.Location) + int.Parse(source.OriginalLocation)).ToString();
                            }
                        }
                    }
                    if (elementAttribut.interactiveModel!=null && elementAttribut.interactiveModel.ModelDic.ContainsKey("rerule"))
                    {
                        if (elementAttribut.interactiveModel.ModelDic["rerule"][0] != null)
                        {
                            if (elementAttribut.interactiveModel.ModelDic["rerule"][0] != null)
                            {
                                string jsonString = elementAttribut.interactiveModel.ModelDic["rerule"][0].ToString();
                                if (!string.IsNullOrWhiteSpace(jsonString) && JsonHelper.IsRightJson(jsonString))
                                {
                                    JArray ja = (JArray)JsonConvert.DeserializeObject(jsonString);
                                    foreach (var jToken in ja)
                                    {
                                        JObject jo = (JObject)jToken;
                                        string index = jo["Index"].ToString();
                                        string length = jo["Length"].ToString();
                                        if (!string.IsNullOrEmpty(index))
                                            source.OriginalLocation = index;
                                        if (!string.IsNullOrEmpty(length))
                                            source.OriginalLocationLen = length;
                                    }
                                }
                            }
                        }
                    }
                    attribute.sourceList.Add(source);
                    dataModel.AttributesList.Add(attribute);
                }

                foreach (ElementNodeModel elementAttribut in elementDataList.Where(a => a.Path.IndexOf("@") > -1 && a.ParentId == elementData.Id))
                {
                    AttributeInfo attribute = new AttributeInfo();
                    attribute.Name = elementAttribut.Path.Split('@')[1];
                    attribute.DictionariesCode = elementAttribut.DictionariesCode;
                    attribute.sourceList = new List<Source>();
                    Source source = new Source();
                    source.ExtValue = elementAttribut.ExtOriginalText;
                    source.IsCheck = "1";
                    source.OriginalText = HttpHelp.EnDataBase64(elementAttribut.OrigianlTextStr);
                    source.ParagraphCode = elementAttribut.ParagraphName;
                    source.SaveValue = elementAttribut.OriginalTextList[0];
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.SourceID = dataContext.DataLayerAns.SF_ID;
                    source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                    source.AnalysisStatus = "1";
                    if (!string.IsNullOrEmpty(source.ExtValue) && (!dataContext.DataLayerAns.IsParagraphAnalysis.HasValue || dataContext.DataLayerAns.IsParagraphAnalysis == false))
                    {
                        source.OriginalLocation = elementAttribut.OrigianlTextStr.IndexOf(source.ExtValue).ToString();
                        if (!string.IsNullOrEmpty(source.OriginalLocation) && source.OriginalLocation != "-1")
                        {
                            source.Location = dataContext.DataLayerAns.FengXiCanShu.Juanzongneirong.IndexOf(elementAttribut.OrigianlTextStr).ToString();
                            if (source.Location != "-1")
                            {
                                source.Location = (int.Parse(source.Location) + int.Parse(source.OriginalLocation)).ToString();
                            }
                        }
                    }
                    if (elementAttribut.interactiveModel!=null && elementAttribut.interactiveModel.ModelDic.ContainsKey("rerule"))
                    {
                        if (elementAttribut.interactiveModel.ModelDic["rerule"][0] != null)
                        {
                            string jsonString = elementAttribut.interactiveModel.ModelDic["rerule"][0].ToString();
                            if (!string.IsNullOrWhiteSpace(jsonString)&&JsonHelper.IsRightJson(jsonString))
                            {
                                JArray ja = (JArray)JsonConvert.DeserializeObject(jsonString);
                                foreach (var jToken in ja)
                                {
                                    JObject jo = (JObject)jToken;
                                    string index = jo["Index"].ToString();
                                    string length = jo["Length"].ToString();
                                    if (!string.IsNullOrEmpty(index))
                                        source.OriginalLocation = index;
                                    if (!string.IsNullOrEmpty(length))
                                        source.OriginalLocationLen = length;
                                }
                            }
                        }
                    }
                    attribute.sourceList.Add(source);
                    dataModel.AttributesList.Add(attribute);
                }
                SourceData sourceData = new SourceData();
                Source sourceModel = new Source();
                sourceModel.ExtValue = elementData.ExtOriginalText;
                sourceModel.IsCheck = "1";
                sourceModel.OriginalText = HttpHelp.EnDataBase64(elementData.OrigianlTextStr);
                sourceModel.ParagraphCode = elementData.ParagraphName;
                sourceModel.SaveValue = elementData.OriginalTextList[0];
                sourceModel.SourceCode = dataContext.DataLayerAns.SourceCode;
                sourceModel.SourceID = dataContext.DataLayerAns.SF_ID;
                sourceModel.SourceFLID = dataContext.DataLayerAns.FL_ID;
                sourceModel.AnalysisStatus = "1";
                sourceModel.OriginalLocation = elementData.OriginalLocation;
                sourceModel.OriginalLocationLen = elementData.OriginalLen;
                //if (elementData.interactiveModel!=null && elementData.interactiveModel.ModelDic.ContainsKey("rerule"))
                //{
                //    if (elementData.interactiveModel.ModelDic["rerule"][0] != null)
                //    {
                //        string jsonString = elementData.interactiveModel.ModelDic["rerule"][0].ToString();
                //        if (!string.IsNullOrWhiteSpace(jsonString)&& JsonHelper.IsRightJson(jsonString))
                //        {
                //            JArray ja = (JArray)JsonConvert.DeserializeObject(jsonString);
                //            foreach (var jToken in ja)
                //            {
                //                JObject jo = (JObject)jToken;
                //                if (jo["Vlaue"].ToString()== sourceModel.ExtValue)
                //                {
                //                    string index = jo["Index"].ToString();
                //                    string length = jo["Length"].ToString();
                //                    if (!string.IsNullOrEmpty(index))
                //                        sourceModel.OriginalLocation = index;
                //                    if (!string.IsNullOrEmpty(length))
                //                        sourceModel.OriginalLocationLen = length;
                //                }
                               
                //            }
                //        }
                //    }
                //}
                sourceData.sourceList = new List<Source>();
                sourceData.sourceList.Add(sourceModel);
                dataModel.sourceData = sourceData;
                datalList.Add(dataModel);
            }
        }

        /// <summary>
        /// xml转换为实体
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <returns></returns>
        public DataSoursModel GetXMLByDataModel(XmlDocument xmlDocument)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeModel(xmlNode, dataModelList, xmlNode.Name, "");
            }
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = new List<DataModel>();
            dataSoursModel.dataModelList = dataModelList;
            return dataSoursModel;
        }
        /// <summary>
        /// xml转换为实体
        /// </summary>
        /// <param name="xmlDocument">需要转换的xmldoc</param>
        /// <returns></returns>
        public DataSoursModel GetXMLByDataModelBackFill(XmlDocument xmlDocument)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeModel(xmlNode, dataModelList, "", "", xmlNode.Name);
            }
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = new List<DataModel>();
            dataSoursModel.dataModelList = dataModelList;
            return dataSoursModel;
        }

        /// <summary>
        /// xml转换为实体
        /// </summary>
        /// <param name="xmlDocument">需要转换的xmldoc</param>
        /// <returns></returns>
        public DataSoursModel GetXMLByDataModelBackFill(XmlDocument xmlDocument, string doctype)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeModels(xmlNode, dataModelList, "", "", doctype, xmlNode.Name);
            }
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = new List<DataModel>();
            dataSoursModel.dataModelList = dataModelList;
            return dataSoursModel;
        }
        /// <summary>
        /// xml转换为实体
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <returns></returns>
        public DataSoursModel GetXMLByDataModelBackID(XmlDocument xmlDocument)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeIDModel(xmlNode, dataModelList, "", "", xmlNode.Name);
            }
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = new List<DataModel>();
            dataSoursModel.dataModelList = dataModelList;
            return dataSoursModel;
        }
        /// <summary>
        /// 根据xml生成datamodelList
        /// </summary>
        /// <param name="xmlDocument">分析数据</param>
        /// <param name="parentName">根节点名称</param>
        public List<DataModel> NodeModelByDataModel(XmlDocument xmlDocument, string parentName)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeModel(xmlNode, dataModelList, "", parentName);
            }
            return dataModelList;
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="elementDataList"></param>
        /// <param name="datalList"></param>
        public void AddDataSources(List<SD_ElementDataModel> elementDataList, List<DataModel> datalList)
        {
            foreach (SD_ElementDataModel elementData in elementDataList.Where(a => a.ED_XmlPath.IndexOf("@") < 0))
            {
                DataModel dataModel = new DataModel();
                dataModel.ID = elementData.ED_ID;
                dataModel.ParentId = elementData.ED_ParentID;
                dataModel.State = "1";
                dataModel.XmlPath = elementData.ED_XmlPath.Replace("\\", "/");
                dataModel.AttributesList = new List<AttributeInfo>();
                foreach (SD_ElementDataModel elementAttribut in elementDataList.Where(a => a.ED_XmlPath.IndexOf("@") > -1 && a.ED_ParentID == elementData.ED_ID))
                {
                    AttributeInfo attribute = new AttributeInfo();
                    attribute.Name = elementAttribut.ED_XmlPath.Split('@')[1];
                    attribute.DictionariesCode = elementAttribut.ED_ConvertCode;
                    attribute.sourceList = new List<Source>();
                    Source source = new Source();
                    source.ExtValue = elementAttribut.ED_ExtValue;
                    source.IsCheck = "1";
                    source.OriginalText = HttpHelp.EnDataBase64(elementAttribut.ED_OriginalText);
                    source.ParagraphCode = elementAttribut.ED_ParagraphSign;
                    source.SaveValue = elementAttribut.ED_SaveValue;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.SourceID = dataContext.DataLayerAns.SF_ID;
                    source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                    source.ExtValue = elementAttribut.ED_ExtValue;
                    if (!string.IsNullOrEmpty(source.ExtValue))
                    {
                        source.OriginalLocation = elementAttribut.ED_OriginalText.IndexOf(source.ExtValue).ToString();
                    }
                    attribute.sourceList.Add(source);
                    dataModel.AttributesList.Add(attribute);
                }
                SourceData sourceData = new SourceData();
                Source sourceModel = new Source();
                sourceModel.ExtValue = elementData.ED_ExtValue;
                sourceModel.IsCheck = "1";
                sourceModel.OriginalText = HttpHelp.EnDataBase64(elementData.ED_OriginalText);
                sourceModel.ParagraphCode = elementData.ED_ParagraphSign;
                sourceModel.SaveValue = elementData.ED_SaveValue;
                sourceModel.SourceCode = dataContext.DataLayerAns.SourceCode;
                sourceModel.SourceID = dataContext.DataLayerAns.SF_ID;
                sourceModel.SourceFLID = dataContext.DataLayerAns.FL_ID;
                sourceData.sourceList = new List<Source>();
                sourceData.sourceList.Add(sourceModel);
                dataModel.sourceData = sourceData;
                datalList.Add(dataModel);
            }
        }

        /// <summary>
        /// 根据根节点获取
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="dataModelList"></param>
        public void NodeChangeModel(XmlNode xmlNode, List<DataModel> dataModelList, string xpath, string parentid, string nodeName = "")
        {
            DataModel dataModel = new DataModel();
            dataModel.ID = Snowflake.Instance().GetId().ToString();
            dataModel.ParentId = parentid;
            dataModel.State = "1";
            if (string.IsNullOrEmpty(nodeName))
            {
                dataModel.XmlPath = xpath + "/" + xmlNode.Name;
                if (xpath == "")
                {
                    dataModel.XmlPath = xmlNode.Name + "/";
                }
            }
            else
            {
                dataModel.XmlPath = nodeName;
            }
            dataModel.XmlPath = dataModel.XmlPath.Replace("//", "/");
            dataModel.AttributesList = new List<AttributeInfo>();
            foreach (XmlAttribute attribute in xmlNode.Attributes)
            {
                if (attribute.Name.ToLower() == "id")
                {
                    dataModel.ID = attribute.Value;
                }
                else
                {
                    AttributeInfo attributemodel = new AttributeInfo();
                    attributemodel.Name = attribute.Name;
                    attributemodel.sourceList = new List<Source>();
                    Source source = new Source();
                    source.ExtValue = attribute.Value;
                    source.IsCheck = "1";
                    source.OriginalText = "";
                    source.ParagraphCode = "";
                    source.SaveValue = attribute.Value;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.SourceID = dataContext.DataLayerAns.SF_ID;
                    source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                    attributemodel.sourceList.Add(source);
                    dataModel.AttributesList.Add(attributemodel);
                }
            }
            SourceData sourceData = new SourceData();
            Source sourceModel = new Source();
            sourceModel.ExtValue = "";
            sourceModel.IsCheck = "1";
            sourceModel.OriginalText = "";
            sourceModel.ParagraphCode = "";
            sourceModel.SaveValue = "";
            sourceModel.SourceCode = dataContext.DataLayerAns.SourceCode;
            sourceModel.SourceID = dataContext.DataLayerAns.SF_ID;
            sourceModel.SourceFLID = dataContext.DataLayerAns.FL_ID;
            sourceData.sourceList = new List<Source>();
            sourceData.sourceList.Add(sourceModel);
            dataModel.sourceData = sourceData;
            dataModelList.Add(dataModel);
            foreach (XmlNode node in xmlNode.ChildNodes)
            {
                NodeChangeModel(node, dataModelList, dataModel.XmlPath, dataModel.ID);
            }

        }

        public void NodeChangeModels(XmlNode xmlNode, List<DataModel> dataModelList, string xpath, string parentid, string sourscode, string nodeName = "")
        {
            DataModel dataModel = new DataModel();
            dataModel.ID = Snowflake.Instance().GetId().ToString();
            dataModel.ParentId = parentid;
            dataModel.State = "1";
            if (string.IsNullOrEmpty(nodeName))
            {
                dataModel.XmlPath = xpath + "/" + xmlNode.Name;
            }
            else
            {
                dataModel.XmlPath = nodeName;
            }

            dataModel.AttributesList = new List<AttributeInfo>();
            foreach (XmlAttribute attribute in xmlNode.Attributes)
            {
                if (attribute.Name.ToLower() == "id")
                {
                    dataModel.ID = attribute.Value;
                }
                else
                {
                    AttributeInfo attributemodel = new AttributeInfo();
                    attributemodel.Name = attribute.Name;
                    attributemodel.sourceList = new List<Source>();
                    Source source = new Source();
                    source.ExtValue = attribute.Value;
                    source.IsCheck = "1";
                    source.OriginalText = "";
                    source.ParagraphCode = "";
                    source.SaveValue = attribute.Value;
                    source.SourceCode = sourscode;
                    source.SourceID = "";
                    attributemodel.sourceList.Add(source);
                    dataModel.AttributesList.Add(attributemodel);
                }

            }
            SourceData sourceData = new SourceData();
            Source sourceModel = new Source();
            sourceModel.ExtValue = "";
            sourceModel.IsCheck = "1";
            sourceModel.OriginalText = "";
            sourceModel.ParagraphCode = "";
            sourceModel.SaveValue = "";
            sourceModel.SourceCode = sourscode;
            sourceModel.SourceID = "";
            sourceData.sourceList = new List<Source>();
            sourceData.sourceList.Add(sourceModel);
            dataModel.sourceData = sourceData;
            dataModelList.Add(dataModel);
            foreach (XmlNode node in xmlNode.ChildNodes)
            {
                NodeChangeModels(node, dataModelList, dataModel.XmlPath, dataModel.ID, sourscode);
            }

        }
        /// <summary>
        /// 根据根节点获取
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="dataModelList"></param>
        public void NodeChangeIDModel(XmlNode xmlNode, List<DataModel> dataModelList, string xpath, string parentid, string nodeName = "")
        {
            DataModel dataModel = new DataModel();
            dataModel.ID = Snowflake.Instance().GetId().ToString();
            dataModel.ParentId = parentid;
            dataModel.State = "1";
            if (string.IsNullOrEmpty(nodeName))
            {
                dataModel.XmlPath = xpath + "/" + xmlNode.Name;
            }
            else
            {
                dataModel.XmlPath = nodeName;
            }

            dataModel.AttributesList = new List<AttributeInfo>();
            foreach (XmlAttribute attribute in xmlNode.Attributes)
            {
                if (attribute.Name.ToLower() == "id")
                {
                    dataModel.ID = Snowflake.Instance().GetId().ToString(); ;
                }
                else
                {
                    AttributeInfo attributemodel = new AttributeInfo();
                    attributemodel.Name = attribute.Name;
                    attributemodel.sourceList = new List<Source>();
                    Source source = new Source();
                    source.ExtValue = attribute.Value;
                    source.IsCheck = "1";
                    source.OriginalText = "";
                    source.ParagraphCode = "";
                    source.SaveValue = attribute.Value;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.SourceID = dataContext.DataLayerAns.SF_ID;
                    source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                    attributemodel.sourceList.Add(source);
                    dataModel.AttributesList.Add(attributemodel);
                }

            }
            SourceData sourceData = new SourceData();
            Source sourceModel = new Source();
            sourceModel.ExtValue = "";
            sourceModel.IsCheck = "1";
            sourceModel.OriginalText = "";
            sourceModel.ParagraphCode = "";
            sourceModel.SaveValue = "";
            sourceModel.SourceCode = dataContext.DataLayerAns.SourceCode;
            sourceModel.SourceID = dataContext.DataLayerAns.SF_ID;
            sourceModel.SourceFLID = dataContext.DataLayerAns.FL_ID;
            sourceData.sourceList = new List<Source>();
            sourceData.sourceList.Add(sourceModel);
            dataModel.sourceData = sourceData;
            dataModelList.Add(dataModel);

            foreach (XmlNode node in xmlNode.ChildNodes)
            {
                NodeChangeIDModel(node, dataModelList, dataModel.XmlPath, dataModel.ID);
            }

        }
        /// <summary>
        /// 根据xpath进行判断节点是否存在，如果不存在则添加
        /// </summary>
        /// <param name="dataModelCaseElmentList">实体集合</param>
        /// <param name="path">路径集合</param>
        /// <returns></returns>
        public string CaseNodeUpdate(List<DataModel> dataModelCaseElmentList, string path)
        {
            
            DataModel dataModel = XmlUtility.XmlUtility.ConditionFirstOrDefaultDataModel(dataModelCaseElmentList, "", path);
            if (dataModel == null)
            {
                string rpath = path;

                //Regex f = new Regex(@"(?<=详情)[\[]\S+[\/]@[^\r]+?]");
                //该规则用于替换掉xpath中的所有条件信息；
                Regex f = new Regex(@"\[[^\[]+?\]");
                MatchCollection mcf = f.Matches(rpath);
                for (int i = 0; i < mcf.Count; i++)
                {
                    rpath = rpath.Replace(mcf[i].Value, "");
                }
                //string xpath = "";
                List<string> rpathList = rpath.Split("/").ToList();
                int lasindex=path.LastIndexOf("/" + rpathList[rpathList.Count - 1]);
                int endIndex = lasindex;
                //if (!path.Substring(lasindex).Contains("["))
                //{
                    rpathList.RemoveAt(rpathList.Count - 1);
                //}
                //else 
                //{
                //    endIndex += rpathList[rpathList.Count - 1].Length+1;
                //}
                
                string xpath = path.Substring(0, endIndex);
                 
                string uid = CaseNodeUpdate(dataModelCaseElmentList, xpath);
                //var nodedatamodel= XmlUtility.XmlUtility.ConditionFirstOrDefaultDataModel(dataModelCaseElmentList, "", xpath);
                //if (nodedatamodel == null)
                //{
                //    uid = CaseNodeUpdate(dataModelCaseElmentList, xpath);
                //}
                //else
                //{
                //    uid = nodedatamodel.ID;
                //}
                if (string.IsNullOrEmpty(uid))
                {
                    return "";
                }

                DataModel dataModelCauseName = new DataModel();
                dataModelCauseName.ID = Snowflake.Instance().GetId().ToString();
                dataModelCauseName.XmlPath = rpath;
                dataModelCauseName.sourceData = new SourceData();
                dataModelCauseName.ParentId = uid;
                dataModelCauseName.sourceData.sourceList = new List<Source>();
                dataModelCauseName.State = "1";
                Source source = new Source();
                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                source.IsCheck = "1";
                dataModelCauseName.sourceData.sourceList.Add(source);
                dataModelCaseElmentList.Add(dataModelCauseName);

                return dataModelCauseName.ID;
            }
            else
            {
                return dataModel.ID;
            }

        }

        /// <summary>
        /// 向上追溯根节点信息
        /// </summary>
        /// <param name="dataModelList">数据源集合</param>
        /// <param name="dataModel">开始追溯的节点</param>
        /// <returns></returns>
        public List<DataModel> SubParentDateModel(List<DataModel> dataModelList, DataModel dataModel)
        {
            List<DataModel> dataList = new List<DataModel>();
            dataList.Add(dataModel);
            List<DataModel> datasModels = dataModelList.Where(a => a.ID == dataModel.ParentId).ToList();
            foreach (DataModel model in datasModels)
            {
                List<DataModel> dataModelValueList = SubParentDateModel(dataModelList, model);
                dataList.AddRange(dataModelValueList);
            }
            return dataList;
        }

        /// <summary>
        /// 向上追溯根节点信息,不包含开始追溯的节点
        /// </summary>
        /// <param name="dataModelList">数据源集合</param>
        /// <param name="dataModel">开始追溯的节点</param>
        /// <returns></returns>
        public List<DataModel> SubParentDateModelNoDM(List<DataModel> dataModelList, DataModel dataModel)
        {
            List<DataModel> dataList = new List<DataModel>();
            //dataList.Add(dataModel);
            List<DataModel> datasModels = dataModelList.Where(a => a.ID == dataModel.ParentId).ToList();
            foreach (DataModel model in datasModels)
            {
                List<DataModel> dataModelValueList = SubParentDateModel(dataModelList, model);
                dataList.AddRange(dataModelValueList);
            }
            return dataList;
        }


        /// <summary>
        /// 获取下级所有子节点
        /// </summary>
        /// <param name="dataModelList">数据源集合</param>
        /// <param name="dataModel">当前数据</param>
        /// <returns></returns>
        public List<DataModel> SubordinateDataModelList(List<DataModel> dataModelList, DataModel dataModel)
        {
            ///事实要素/合同履行/详情/还款情况/详情/还款详情/分期还款
            ///事实要素/合同履行/详情/还款情况/详情/还款详情/分期还款/详情
            List<DataModel> dataList = new List<DataModel>();
            if (dataModel != null)
            {
                dataList.Add(dataModel);
                List<DataModel> datasModels = dataModelList.Where(a => a.ParentId == dataModel.ID && a.ID != dataModel.ID).ToList();
                foreach (DataModel model in datasModels)
                {
                    List<DataModel> dataModelValueList = SubordinateDataModelList(dataModelList, model);
                    dataList.AddRange(dataModelValueList);
                }
            }
            return dataList;
        }
        /// <summary>
        /// 重置信息ID
        /// </summary>
        /// <param name="dataModelList"></param>
        /// <param name="parentID"></param>
        public void DataModelIDByReset(List<DataModel> dataModelList, string parentID, string parentIDNew)
        {
            List<DataModel> dataList = dataModelList.Where(a => a.ParentId == parentID && a.ID != parentID).ToList();
            foreach (DataModel dataModel in dataList)
            {
                string id = dataModel.ID;
                if (id.IndexOf(",") == -1)
                {
                    dataModel.ID = Snowflake.Instance().GetId().ToString();
                }
                dataModel.ParentId = parentIDNew;
                DataModelIDByReset(dataModelList, id, dataModel.ID);
            }
            
        }
        /// <summary>
        /// 重置信息ID
        /// </summary>
        /// <param name="dataModelList"></param>
        /// <param name="parentID"></param>
        public void DataModelIDByResets(List<DataModel> dataModelList, string parentID, string parentIDNew)
        {
            List<DataModel> dataList = dataModelList.Where(a => a.ParentId == parentID).ToList();
            foreach (DataModel dataModel in dataList)
            {
                string id = dataModel.ID;
                dataModel.ID = Snowflake.Instance().GetId().ToString();
                dataModel.ParentId = parentIDNew;
                DataModelIDByResets(dataModelList, id, dataModel.ID);
            }
        }
        /// <summary>
        /// 重置信息ID并记录重置前后的节点Id
        /// </summary>
        /// <param name="dataModelList"></param>
        /// <param name="parentID"></param>
        public void DataModelIDByResetAndRecord(List<DataModel> dataModelList, string parentID, string parentIDNew, string elementType ,List<FactElementNodeCorredRecord> corredRecords, out List<FactElementNodeCorredRecord> resultRecords)
        {
            if (corredRecords == null)
                corredRecords = new List<FactElementNodeCorredRecord>();
            List<DataModel> dataList = dataModelList.Where(a => a.ParentId == parentID && a.ID != parentID).ToList();
            foreach (DataModel dataModel in dataList)
            {
                string id = dataModel.ID;
                if (id.IndexOf(",") == -1)
                {
                    dataModel.ID = Snowflake.Instance().GetId().ToString();
                }
                dataModel.ParentId = parentIDNew;

                FactElementNodeCorredRecord corredRecord = new FactElementNodeCorredRecord();
                corredRecord.ElementType = elementType;
                corredRecord.MergeBeforeId = id;
                corredRecord.MergeAfterId = dataModel.ID;
                corredRecords.Add(corredRecord);
                DataModelIDByResetAndRecord(dataModelList, id, dataModel.ID,elementType,corredRecords,out resultRecords);
            }
            resultRecords = corredRecords;
        }

        /// <summary>
        /// 将XML转换为数据模型
        /// </summary>
        /// <param name="xmlDocument">需要转换的XML</param>
        /// <returns></returns>
        public DataSoursModel GetXMLByDataModelBack(XmlDocument xmlDocument)
        {
            List<DataModel> dataModelList = new List<DataModel>();
            foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
            {
                NodeChangeModelBack(xmlNode, dataModelList, xmlNode.Name, "");
            }
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = new List<DataModel>();
            dataSoursModel.dataModelList = dataModelList;
            return dataSoursModel;
        }

        /// <summary>
        /// 根据根节点获取
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="dataModelList"></param>
        public void NodeChangeModelBack(XmlNode xmlNode, List<DataModel> dataModelList, string xpath, string parentid, string nodeName = "")
        {
            DataModel dataModel = new DataModel();
            dataModel.ID = Snowflake.Instance().GetId().ToString();
            dataModel.ParentId = parentid;
            dataModel.State = "1";
            if (string.IsNullOrEmpty(nodeName))
            {
                dataModel.XmlPath = xmlNode.Name;
            }
            else
            {
                dataModel.XmlPath = nodeName + "/" + xmlNode.Name;
            }

            dataModel.AttributesList = new List<AttributeInfo>();
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attribute in xmlNode.Attributes)
                {
                    if (attribute.Name.ToLower() == "id")
                    {
                        dataModel.ID = attribute.Value;
                    }
                    else
                    {
                        AttributeInfo attributemodel = new AttributeInfo();
                        attributemodel.Name = attribute.Name;
                        attributemodel.sourceList = new List<Source>();
                        Source source = new Source();
                        source.ExtValue = attribute.Value;
                        source.IsCheck = "1";
                        source.OriginalText = "";
                        source.ParagraphCode = "";
                        source.SaveValue = attribute.Value;
                        source.SourceCode = dataContext.DataLayerAns.SourceCode;
                        source.SourceID = dataContext.DataLayerAns.SF_ID;
                        source.SourceFLID = dataContext.DataLayerAns.FL_ID;
                        attributemodel.sourceList.Add(source);
                        dataModel.AttributesList.Add(attributemodel);
                    }

                }
            }
            SourceData sourceData = new SourceData();
            Source sourceModel = new Source();
            sourceModel.ExtValue = "";
            sourceModel.IsCheck = "1";
            sourceModel.OriginalText = "";
            sourceModel.ParagraphCode = "";
            sourceModel.SaveValue = "";
            sourceModel.SourceCode = dataContext.DataLayerAns.SourceCode;
            sourceModel.SourceID = dataContext.DataLayerAns.SF_ID;
            sourceModel.SourceFLID = dataContext.DataLayerAns.FL_ID;
            sourceData.sourceList = new List<Source>();
            sourceData.sourceList.Add(sourceModel);
            dataModel.sourceData = sourceData;
            dataModelList.Add(dataModel);
            foreach (XmlNode node in xmlNode.ChildNodes)
            {
                NodeChangeModelBack(node, dataModelList, dataModel.XmlPath, dataModel.ID, dataModel.XmlPath);
            }

        }
        #endregion

        #region 实体转换操作
        /// <summary>
        /// DataModel转换XML
        /// </summary>
        /// <param name="dataModelList">实体对象</param>
        /// <param name="parentID">父级ID</param>
        /// <param name="empty">是否空节点</param>
        /// <param name="isEvid">是否证据要素数据</param>
        /// <returns></returns>
        public XmlDocument DataModelByXml(List<DataModel> dataModelList, string parentID, bool empty = true,bool isEvid=false)
        {
            if (dataModelList != null && dataModelList.Any())
            {
                dataModelList = dataModelList.Where(a => a.State != "0").ToList();
            }
            XmlDocument xmlDocument = new XmlDocument();
            DataModel dataModelRoot = null;
            if(isEvid)
                dataModelRoot = dataModelList?.FirstOrDefault(a => a.ParentId == parentID && a.XmlPath.Contains("证据要素"));
            else
                dataModelRoot = dataModelList?.FirstOrDefault(a => a.ParentId == parentID);
            if (dataModelRoot!=null)
            {
                List<string> xmlrootList = dataModelRoot?.XmlPath.Split('/').ToList();
                string nodename = "";
                if (xmlrootList != null && xmlrootList.Any())
                {
                    nodename = xmlrootList[xmlrootList.Count - 1];
                    if (nodename == "")
                    {
                        nodename = dataModelRoot.XmlPath.Replace("/", "");
                    }
                }
                else
                {
                    //.Replace("/", "")有必要替换吗？
                    nodename = dataModelRoot?.XmlPath?.Replace("/", "");
                }
                Regex r = new Regex(@"\[[^,，。;；/]*?\]");
                MatchCollection mc = r.Matches(nodename);
                string name = "";
                if (mc.Count > 0)
                {
                    for (int i = 0; i < mc.Count; i++)
                    {
                        name = nodename.Replace(mc[i].Value, "");
                    }
                }
                else
                {
                    name = nodename;
                }
                XmlElement xmlElementRoot = xmlDocument.CreateElement(name);
                if (dataModelRoot.AttributesList != null)
                {
                    foreach (var attitem in dataModelRoot.AttributesList)
                    {
                        if (attitem.Name != "id")
                        {
                            xmlElementRoot.SetAttribute(attitem.Name, attitem.sourceList.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue);
                        }

                    }
                }
                xmlElementRoot.SetAttribute("id", dataModelRoot.ID);
                XmlNodeDocDataModel(xmlElementRoot, xmlDocument, dataModelRoot.ID, dataModelList);
                xmlDocument.AppendChild(xmlElementRoot);
                if (xmlDocument != null && empty)
                {
                    xmlDocument = EscapeNodeIndexAndBlank(xmlDocument);
                }
            }
            return xmlDocument;
        }

        /// <summary>
        /// 父子级别节点添加
        /// </summary>
        /// <param name="xmlElementRoot">父节点</param>
        /// <param name="xmlDocument">数据对象</param>
        /// <param name="parentID">上级ID</param>
        /// <param name="dataModelList">数据源</param>
        private void XmlNodeDocDataModel(XmlElement xmlElementRoot, XmlDocument xmlDocument, string parentID, List<DataModel> dataModelList)
        {

            List<DataModel> chanNodelModelList = dataModelList.Where(a => a.ParentId == parentID && a.ID != parentID).ToList();
            foreach (DataModel dataModel in chanNodelModelList)
            {
                string nodename = dataModel.XmlPath.Split('/')[dataModel.XmlPath.Split('/').Length - 1];
                if (string.IsNullOrEmpty(nodename))
                {
                    nodename = dataModel.XmlPath.Replace("/", "");
                }
                Regex r = new Regex(@"\[[^;；/]*?\]");
                MatchCollection mc = r.Matches(nodename);
                string name = "";
                if (mc.Count > 0)
                {
                    for (int i = 0; i < mc.Count; i++)
                    {
                        name = nodename.Replace(mc[i].Value, "");
                    }
                }
                else
                {
                    name = nodename;
                }
                try
                {
                    XmlElement xmlElementNode33l = xmlDocument.CreateElement(name);
                }
                catch (System.Exception  f)
                {
                    //???
                    string gff = "";
                }
                XmlElement xmlElementNodel = xmlDocument.CreateElement(name);

                xmlElementNodel.SetAttribute("id", dataModel.ID);
                if (dataModel.AttributesList != null)
                {
                    foreach (var attirValue in dataModel.AttributesList)
                    {
                        if (attirValue.sourceList.FirstOrDefault(a => a.IsCheck == "1") != null)
                        {
                            string saveValue = attirValue.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            if (!string.IsNullOrEmpty(saveValue))
                            {
                                try
                                {
                                    xmlElementNodel.SetAttribute(attirValue.Name, saveValue);
                                }
                                catch (System.Exception ef)
                                {

                                    string ff = "";
                                }

                            }
                        }

                    }
                }
                XmlNodeDocDataModel(xmlElementNodel, xmlDocument, dataModel.ID, dataModelList);
                xmlElementRoot.AppendChild(xmlElementNodel);
            }
        }
        /// <summary>
        /// 节点去重
        /// </summary>
        /// <param name="docxml">内容实体</param>
        /// <returns></returns>
        public static XmlDocument EscapeNodeIndexAndBlank(XmlDocument docxml)
        {
            docxml = EscapeBlank(docxml);
            return docxml;
        }

        /// <summary>
        /// 去除xml中的空节点
        /// </summary>//*[not(attribute::*) and not (child::*)]
        /// <param name="second">待去除xml</param>
        /// <returns>取出后的结果</returns>
        protected static XmlDocument EscapeBlank(XmlDocument second)
        {
            XmlNodeList blanks = second.SelectNodes("//descendant-or-self::*[not(attribute::*[name()!='id']) and attribute::id and not(child::*)]");//取无属性 无子节点的节点
            while (blanks.Count > 0)
            {
                bool flag = true;
                foreach (XmlNode node in blanks)
                {
                    if (node.ParentNode.ParentNode != null)
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                    else
                    {
                        flag = false;
                    }
                }
                blanks = second.SelectNodes("//descendant-or-self::*[not(attribute::*[name()!='id']) and attribute::id and not(child::*)]");//递归查询
                if (!flag)
                    break;
            }
            return second;


           
        }

        /// <summary>
        /// 对datamodel集合去空节点
        /// </summary>
        /// <param name="dataModelList">节点集合</param>
        /// <param name="dataModelRoot">根节点</param>
        /// <param name="isEvid">是否证据要素数据</param>
        /// <returns></returns>

        public List<DataModel> EmptyNode(List<DataModel> dataModelList, DataModel dataModelRoot,bool isEvid=false)
        {
            XmlDocument xmlDocument = DataModelByXml(dataModelList, dataModelRoot.ID,isEvid=true);

            XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//@id");
            List<DataModel> dataModelsRule = new List<DataModel>();

            foreach (XmlNode node in xmlNodeList)
            {
                dataModelsRule.Add(dataModelList.FirstOrDefault(a => a.ID == node.Value));
            }
            return dataModelsRule;
        }
        #endregion
    }

}
